//
//  JKTabBarController.m
//  Baisi
//
//  Created by albert on 16/3/13.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKTabBarController.h"
#import "JKEssenceViewController.h"
#import "JKNewViewController.h"
#import "JKFriendTrendsViewController.h"
#import "JKMeViewController.h"
#import "JKTabBar.h"
#import "JKNavigationController.h"
#import "JKPublishView.h"
#import "AppDelegate.h"

@interface JKTabBarController ()
/** 发布按钮 */
@property (nonatomic, strong) UIButton *composeButton;

/** 是否允许自动旋转 */
@property (nonatomic, assign) BOOL canAutoRotate;
@end

static NSUInteger const tabBarBtnCount = 5; // 底部按钮的数量

@implementation JKTabBarController

+ (void)initialize{
    //字典的key到NSAttributedString.h里面找
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attr[NSForegroundColorAttributeName] = [UIColor grayColor];
    
    NSMutableDictionary *selectedAttr = [NSMutableDictionary dictionary];
    selectedAttr[NSFontAttributeName] = attr[NSFontAttributeName];
    selectedAttr[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    
    //通过appearance统一设置所有UITabBarItem的文字属性
    //后面带有的UI_APPEARANCE_SELECTOR方法，都可以通过appearance统一设置
    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:attr forState:UIControlStateNormal];
    [item setTitleTextAttributes:selectedAttr forState:UIControlStateHighlighted];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
    [self.tabBar addSubview:self.composeButton];
    
    self.composeButton.height = 49 + 5;
    self.composeButton.width = self.tabBar.width / (tabBarBtnCount - 0.2);
    self.composeButton.centerX = self.tabBar.centerX;
    self.composeButton.centerY = 24.5;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加子控制器;
    [self setupChildViewController:[[JKEssenceViewController alloc] init] title:@"精华" normalImage:@"tabBar_essence_icon" selectedImage:@"tabBar_essence_click_icon"];
    
    [self setupChildViewController:[[JKNewViewController alloc] init] title:@"最新" normalImage:@"tabBar_new_icon" selectedImage:@"tabBar_new_click_icon"];
    
    [self setupChildViewController:[[UIViewController alloc] init] title:nil normalImage:nil selectedImage:nil];
    
    [self setupChildViewController:[[JKFriendTrendsViewController alloc] init] title:@"关注" normalImage:@"tabBar_friendTrends_icon" selectedImage:@"tabBar_friendTrends_click_icon"];
    
    [self setupChildViewController:[[JKMeViewController alloc] initWithStyle:(UITableViewStyleGrouped)] title:@"我" normalImage:@"tabBar_me_icon" selectedImage:@"tabBar_me_click_icon"];
    
    UIButton *composeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    composeButton.adjustsImageWhenHighlighted = NO;
    [composeButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:(UIControlStateNormal)];
    [composeButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:(UIControlStateHighlighted)];
    composeButton.imageEdgeInsets = UIEdgeInsetsMake(5, 0, 0, 0);
    [composeButton addTarget:self action:@selector(composeButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
    self.composeButton = composeButton;
    
    // 对于redonly的属性，可以使用kvc赋值，因为kvc是直接访问成员变量的
    [self setValue:[[JKTabBar alloc] initWithFrame:self.tabBar.frame] forKeyPath:@"tabBar"];
    
    self.selectedIndex = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canRotate) name:JKTurnOnAutoRotateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canNotRotate) name:JKTurnOffAutoRotateNotification object:nil];
}

- (UIViewController *)childViewControllerForHomeIndicatorAutoHidden{
    return nil;
}

- (BOOL)prefersHomeIndicatorAutoHidden{
    return self.canAutoRotate;
}

- (void)canRotate{
    self.canAutoRotate = YES;
    [(AppDelegate *)[UIApplication sharedApplication].delegate setIsCanAutoRotate:YES];
    
    if (@available(iOS 11.0, *)) {
        [self setNeedsUpdateOfHomeIndicatorAutoHidden];
    } else {
        // Fallback on earlier versions
    }
}

- (void)canNotRotate{
    self.canAutoRotate = NO;
    [(AppDelegate *)[UIApplication sharedApplication].delegate setIsCanAutoRotate:NO];
    
    if (@available(iOS 11.0, *)) {
        [self setNeedsUpdateOfHomeIndicatorAutoHidden];
    } else {
        // Fallback on earlier versions
    }
}

- (BOOL)shouldAutorotate{
    return NO;//self.canAutoRotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskPortrait;//self.canAutoRotate ? UIInterfaceOrientationMaskPortrait |UIInterfaceOrientationMaskLandscapeRight : UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationPortrait;//self.canAutoRotate ? UIInterfaceOrientationPortrait | UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait ;
} //*/

- (void)composeButtonClick{
    
    [JKPublishView show];
}

/**
 *  初始化子控制器
 *
 *  @param viewController 子控制器类型
 *  @param title          标题
 *  @param normalImage    普通状态图片名字
 *  @param selectedImage  选中状态名字
 */
- (void)setupChildViewController:(UIViewController *)viewController title:(NSString *)title normalImage:(NSString *)normalImage selectedImage:(NSString *)selectedImage{
    
    //设置文字、图片和背景
    viewController.title = title;
    
    if (normalImage) {
        
        viewController.tabBarItem.image = [[UIImage imageNamed:normalImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    
    if (selectedImage) {
        
        viewController.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    
    //在这里访问控制器的view，会导致四个控制器在app启动的时候就全部创建，这样不合理
    //我们需要在用户点击的时候再创建
    //    viewController.view.backgroundColor = RandomColor;
    
    //包装一个导航控制器，添加导航控制器为tabBarController的子控制器
    JKNavigationController *nav = [[JKNavigationController alloc] initWithRootViewController:viewController];
    nav.tabBarItem.tag = self.childViewControllers.count;
    
    [self addChildViewController:nav];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSLog(@"self.selectedIndex----->%zd item.tag----->%zd", self.selectedIndex, item.tag);
    
    //发出一个通知
    
    if (item.tag == self.selectedIndex) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JKTabBarDoubleTapRefreshNotification object:nil userInfo:nil];
    }
}
@end
